package com.bestom.t9.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


import com.bestom.t9.MyApp;
import com.bestom.t9.R;
//import com.bestom.t9.service.SerialPortService;
import com.bestom.t9.utils.BinaryDataConversion;
import com.bestom.t9mod.commons.utils.DataTurn;
import com.bestom.t9mod.core.api.PowerApi;
import com.suke.widget.SwitchButton;



import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

import android_serialport_api.SerialPort;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class PowerActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "PowerActivity";
    private Activity mActivity;
    private Context mContext;
    private Unbinder mUnbinder;
    private PowerActivity self;


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.switcher_4G)
    SwitchButton switcher4G;
    @BindView(R.id.switcher_USB7)
    SwitchButton switcherUsb7;
    @BindView(R.id.switcher_USB6)
    SwitchButton switcherUsb6;
    @BindView(R.id.switcher_USB5)
    SwitchButton switcherUsb5;
    @BindView(R.id.switcher_USB4)
    SwitchButton switcherUsb4;
    @BindView(R.id.switcher_USB3)
    SwitchButton switcherUsb3;
    @BindView(R.id.switcher_USB2)
    SwitchButton switcherUsb2;
    @BindView(R.id.switcher_USB1)
    SwitchButton switcherUsb1;
    @BindView(R.id.button3)
    Button button3;
    @BindView(R.id.button4)
    Button button4;
    @BindView(R.id.button5)
    Button button5;
    @BindView(R.id.button6)
    Button button6;
    @BindView(R.id.button7)
    Button button7;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_power);

        mContext = this;
        mActivity = this;
        self = this;
        mUnbinder = ButterKnife.bind(mActivity);
        toolbar.setTitle(getString(R.string.toolbar_title));
//        stopService();
        // 设置广播信息过滤
        IntentFilter filter = new IntentFilter();
        filter.addAction("state");

        // 注册蓝牙搜索广播接收者，接收并处理搜索结果
        registerReceiver(stateReceiver, filter);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        isOpen = mPowerApi.serialIsOpen();
        if (isOpen) {
//            initData();
//            initPowerState();
            setButClick();
            setListener();
            int data = mPowerApi.getPowerState();
            Log.d("PowerActivity", "接口返回的十进制数据为： " + data);
            setSwitchState(data);
        } else {
            setNotClick();
            Toast.makeText(getApplicationContext(), "打开串口失败，无法进行操作", Toast.LENGTH_LONG).show();
        }
    }

    private void initData() {
        mDataTurn = new DataTurn();
        mBinaryDataConversion = new BinaryDataConversion();
    }

    private void setNotClick() {
        switcher4G.setEnabled(false);
        switcherUsb7.setEnabled(false);
        switcherUsb6.setEnabled(false);
        switcherUsb5.setEnabled(false);
        switcherUsb4.setEnabled(false);
        switcherUsb3.setEnabled(false);
        switcherUsb2.setEnabled(false);
        switcherUsb1.setEnabled(false);
        button3.setEnabled(false);
        button4.setEnabled(false);
        button5.setEnabled(false);
        button6.setEnabled(false);
        button7.setEnabled(false);
    }

    private void setButClick(){
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);
        button5.setOnClickListener(this);
        button6.setOnClickListener(this);
        button7.setOnClickListener(this);
    }

    /**
     * 将byte转换为bai一个长度为8的byte数组，数组每个值代表bit
     */
    public static byte[] getBooleanArray(byte b) {
        byte[] array = new byte[8];
        for (int i = 7; i >= 0; i--) {
            array[i] = (byte) (b & 1);
            b = (byte) (b >> 1);
        }
        return array;
    }
    public byte[] intToByteArray(int n) {
        byte[] b = new byte[4];
        b[0] = (byte) (n & 0xff);
        b[1] = (byte) (n >> 8 & 0xff);
        b[2] = (byte) (n >> 16 & 0xff);
        b[3] = (byte) (n >> 24 & 0xff);
        return b;
    }
    private void setSwitchState(int data){

        byte[] bytes = getBooleanArray(intToByteArray(data)[0]);
        for (int i = 0; i < 8; i++) {
            Log.d("PowerActivity", "parseHexStr2Byte " + i + " is : " + bytes[i]);
        }

        if (bytes[0] == 1) {
            switcher4G.setChecked(true);
        } else {
            switcher4G.setChecked(false);
        }
        if (bytes[1] == 1) {
            switcherUsb7.setChecked(true);
        } else {
            switcherUsb7.setChecked(false);
        }
        if (bytes[2] == 1) {
            switcherUsb6.setChecked(true);
        } else {
            switcherUsb6.setChecked(false);
        }
        if (bytes[3] == 1) {
            switcherUsb5.setChecked(true);
        } else {
            switcherUsb5.setChecked(false);
        }
        if (bytes[4] == 1) {
            switcherUsb4.setChecked(true);
        } else {
            switcherUsb4.setChecked(false);
        }
        if (bytes[5] == 1) {
            switcherUsb3.setChecked(true);
        } else {
            switcherUsb3.setChecked(false);
        }
        if (bytes[6] == 1) {
            switcherUsb2.setChecked(true);
        } else {
            switcherUsb2.setChecked(false);
        }
        if (bytes[7] == 1) {
            switcherUsb1.setChecked(true);
        } else {
            switcherUsb1.setChecked(false);
        }

    }

    private void setViewState(byte[] parseHexStr2Byte) {


        if (parseHexStr2Byte != null) {
            byte[] bytes = getBooleanArray(parseHexStr2Byte[0]);
            for (int i = 0; i < 8; i++) {
                Log.d("PowerActivity", "parseHexStr2Byte " + i + " is : " + bytes[i]);
            }

            if (bytes[0] == 1) {
                switcher4G.setChecked(true);
            } else {
                switcher4G.setChecked(false);
            }
            if (bytes[1] == 1) {
                switcherUsb7.setChecked(true);
            } else {
                switcherUsb7.setChecked(false);
            }
            if (bytes[2] == 1) {
                switcherUsb6.setChecked(true);
            } else {
                switcherUsb6.setChecked(false);
            }
            if (bytes[3] == 1) {
                switcherUsb5.setChecked(true);
            } else {
                switcherUsb5.setChecked(false);
            }
            if (bytes[4] == 1) {
                switcherUsb4.setChecked(true);
            } else {
                switcherUsb4.setChecked(false);
            }
            if (bytes[5] == 1) {
                switcherUsb3.setChecked(true);
            } else {
                switcherUsb3.setChecked(false);
            }
            if (bytes[6] == 1) {
                switcherUsb2.setChecked(true);
            } else {
                switcherUsb2.setChecked(false);
            }
            if (bytes[7] == 1) {
                switcherUsb1.setChecked(true);
            } else {
                switcherUsb1.setChecked(false);
            }
        }

    }

    private void initPowerState() {

        byte[] bytes = mDataTurn.HexToByteArr("553a040598");

        // 写入数据
        try {
            mOutputStream.write(bytes);
            mOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private BroadcastReceiver stateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("state".equals(action)) {
                String state = intent.getStringExtra("state");

                parseHexStr2Byte = parseHexStr2Byte(state);
                Log.d("PowerActivity", "已收到广播 state is : " + state);
                Log.d("PowerActivity", "已收到广播 parseHexStr2Byte is : " + Arrays.toString(parseHexStr2Byte));
                setViewState(parseHexStr2Byte);
                data = Integer.valueOf(state, 16);
                Log.d("PowerActivity", "已收到广播 data is : " + data);

            }
        }
    };


    private int data;
    private byte[] parseHexStr2Byte;

    public byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }


    private BinaryDataConversion mBinaryDataConversion;
    private SerialPort mSerialPort;
    private InputStream mInputStream;
    private OutputStream mOutputStream;
    private DataTurn mDataTurn;
    private boolean isOpen;

    private boolean openSerialPort() {

        /*mSerialPort = SerialPortService.mSerialPort;
        if (mSerialPort == null)
            return false;
        // 获取输入输出流
        mInputStream = mSerialPort.getInputStream();
        mOutputStream = mSerialPort.getOutputStream();*/
        return true;
    }

    private void stopService() {
        MyApp.getApplication().stopService();
    }

    private void startService() {
        if (mInputStream != null) {
            try {
                mInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mOutputStream != null) {
            try {
                mOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mSerialPort.close();

        MyApp.getApplication().startService();
    }

    private void setViewListener() {


        switcherUsb1.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    sendInstruct(7, 1);
                } else {
                    sendInstruct(7, 0);
                }
            }
        });
        switcherUsb2.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    sendInstruct(6, 1);
                } else {
                    sendInstruct(6, 0);
                }
            }
        });
        switcherUsb3.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    sendInstruct(5, 1);
                } else {
                    sendInstruct(5, 0);
                }
            }
        });
        switcherUsb4.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    sendInstruct(4, 1);
                } else {
                    sendInstruct(4, 0);
                }
            }
        });
        switcherUsb5.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    sendInstruct(3, 1);
                } else {
                    sendInstruct(3, 0);
                }
            }
        });
        switcherUsb6.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    sendInstruct(2, 1);
                } else {
                    sendInstruct(2, 0);
                }
            }
        });
        switcherUsb7.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    sendInstruct(1, 1);
                } else {
                    sendInstruct(1, 0);
                }
            }
        });
        switcher4G.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    sendInstruct(0, 1);
                } else {
                    sendInstruct(0, 0);
                }
            }
        });

    }

    PowerApi mPowerApi = new PowerApi();
    private void setListener() {

        switcherUsb1.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                boolean success;
                if (isChecked) {
                    success = mPowerApi.openSinglePower(7);
                } else {
                    success = mPowerApi.closeSinglePower(7);
                }
                if (!success){
                    switcherUsb1.setChecked(!isChecked);
                }
            }
        });
        switcherUsb2.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                boolean success;
                if (isChecked) {
                    success = mPowerApi.openSinglePower(6);
                } else {
                    success = mPowerApi.closeSinglePower(6);
                }
                if (!success){
                    switcherUsb2.setChecked(!isChecked);
                }
            }
        });
        switcherUsb3.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                boolean success;
                if (isChecked) {
                    success = mPowerApi.openSinglePower(5);
                } else {
                    success = mPowerApi.closeSinglePower(5);
                }
                if (!success){
                    switcherUsb3.setChecked(!isChecked);
                }
            }
        });
        switcherUsb4.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                boolean success;
                if (isChecked) {
                    success = mPowerApi.openSinglePower(4);
                } else {
                    success = mPowerApi.closeSinglePower(4);
                }
                if (!success){
                    switcherUsb4.setChecked(!isChecked);
                }
            }
        });
        switcherUsb5.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                boolean success;
                if (isChecked) {
                    success = mPowerApi.openSinglePower(3);
                } else {
                    success = mPowerApi.closeSinglePower(3);
                }
                if (!success){
                    switcherUsb5.setChecked(!isChecked);
                }
            }
        });
        switcherUsb6.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                boolean success;
                if (isChecked) {
                    success = mPowerApi.openSinglePower(2);
                } else {
                    success = mPowerApi.closeSinglePower(2);
                }
                if (!success){
                    switcherUsb6.setChecked(!isChecked);
                }
            }
        });
        switcherUsb7.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                boolean success;
                if (isChecked) {
                    success = mPowerApi.openSinglePower(1);
                } else {
                    success = mPowerApi.closeSinglePower(1);
                }
                if (!success){
                    switcherUsb7.setChecked(!isChecked);
                }
            }
        });
        switcher4G.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                boolean success;
                if (isChecked) {
                    success = mPowerApi.openSinglePower(0);
                } else {
                    success = mPowerApi.closeSinglePower(0);
                }
                if (!success){
                    switcher4G.setChecked(!isChecked);
                }
            }
        });
    }

    private void sendInstruct(int bit, int state) {

        int regData;
        if (state == 1) {
            regData = mBinaryDataConversion.computRegByteData(data, bit);
        } else {
            regData = mBinaryDataConversion.computRegOpenByteData(data, bit);
        }
        String hexString = Integer.toHexString(regData);
        String hex;

        Log.d("PowerActivity", "hexString的值为 : " + hexString + ", 长度为: " + hexString.length());
        if (hexString.length() == 1) {
            hex = "553a05020" + hexString;
        } else {
            hex = "553a0502" + hexString;
        }

        Log.d("PowerActivity", "组合结果为 : " + hex);

        String result = mBinaryDataConversion.makeChecksum(hex);
        Log.d("PowerActivity", "前五组16进制和为 : " + result);

        int resultLength = result.length();

        // "553a0502 + hexString + result" 为控制电源状态的指令
        Log.d("PowerActivity", "写入指令  : " + hex + result.substring(resultLength - 2, resultLength));
        byte[] bytes = mDataTurn.HexToByteArr(hex + result.substring(resultLength - 2, resultLength));
        // 写入数据
        try {
            mOutputStream.write(bytes);
            mOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        initPowerState();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.power, menu);

        menu.findItem(R.id.openAll).setVisible(isAllOpen());
        menu.findItem(R.id.closeAll).setVisible(isAllOpen());
        menu.findItem(R.id.setMtu).setVisible(true);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.openAll:
                openAll();
                break;
            case R.id.closeAll:
                closeAll();
                break;
            default:
        }
        return super.onOptionsItemSelected(item);
    }

    public void closeAll() {
        /*writeHexToBoard("553a05020096");
        data = 0;
        parseHexStr2Byte = parseHexStr2Byte("00");
        setViewState(parseHexStr2Byte);*/
        boolean success = mPowerApi.closeAllPower();
        if (success)
            setSwitchState(0);
    }

    public void openAll() {
        /*writeHexToBoard("553a0502ff95");
        data = 255;
        parseHexStr2Byte = parseHexStr2Byte("FF");
        setViewState(parseHexStr2Byte);*/
        boolean success = mPowerApi.openAllPower();
        if (success)
            setSwitchState(255);
    }

    private void writeHexToBoard(String inHex) {

        Log.d(TAG, "writeHexToBoard");

        if (mInputStream == null)
            return;

        // "553a040396" 为读取电量指令
        byte[] bytes = mDataTurn.HexToByteArr(inHex);
        Log.d("PowerActivity", "写入指令  : " + inHex);
        // 写入数据
        try {
            mOutputStream.write(bytes);
            mOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean isAllOpen() {
        return true;
    }

    @Override
    protected void onDestroy() {
//        startService();
        unregisterReceiver(stateReceiver);
        mUnbinder.unbind();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id){
            case R.id.button3:

                mPowerApi.setRunTime(mContext,3000);

                break;
            case R.id.button4:

                mPowerApi.setRunTime(mContext,10000);

                break;
            case R.id.button5:

                mPowerApi.setRunTime(mContext,20000);

                break;
            case R.id.button6:

                mPowerApi.stopReadElectric(mContext);

                break;
            case R.id.button7:

                mPowerApi.startReadElectric(mContext);

                break;
            default:
        }
    }
}
